import CryptoJS from "crypto-js";

//解密方法
export function Decrypt(word: string, aesKey: string, ivKey: string) {
  const encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  const key = CryptoJS.enc.Utf8.parse(aesKey); //十六位十六进制数作为密钥
  const iv = CryptoJS.enc.Utf8.parse(ivKey); //十六位十六进制数作为密钥偏移量
  const decrypt = CryptoJS.AES.decrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}

//加密方法
export function Encrypt(word: string, aesKey: string, ivKey: string) {
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const key = CryptoJS.enc.Utf8.parse(aesKey);
  const iv = CryptoJS.enc.Utf8.parse(ivKey);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  // return encrypted.ciphertext.toString().toUpperCase(); //大写
  return encrypted.ciphertext.toString();
}

export function createSign(params: any[], key: string) {
  params = params.sort();
  let paramVals = "";
  for (let i = 0; i < params.length; i++) {
    if (
      typeof params[i][1] != "object" &&
      params[i][1] !== null &&
      params[i][1] !== undefined &&
      params[i][1] !== ""
    ) {
      paramVals += params[i][0] + "=" + params[i][1] + "&";
    }
  }
  //加上app key[后台配置API的account key]
  paramVals += "key=" + key;

  //MD5加密
  const hash = CryptoJS.MD5(paramVals);
  //转换大写
  return ("" + hash).toUpperCase();
}

export function signParams(
  params: { [x: string]: any; sign: string },
  appKey: string
) {
  // let len = Object.getOwnPropertyNames(params).length;
  const arr = [];
  for (const key in params) {
    const tmp = [key, params[key]];
    arr.push(tmp);
  }
  const sign = createSign(arr, appKey);
  params.sign = sign;
  return params;
}
